package com.jdy.haoduoai.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PackageDetails;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

//import com.jdy.haoduoai.R;

/**
 * 会员中心
 * 
 * @author Hufei
 * 
 */
public class MembershipCenterActivity extends BaseActivity implements
    OnClickListener {

  @InjectView(id = R.id.packages_layout)
  private LinearLayout packageRootLayout;
  @InjectView(id = R.id.button1, click = true)
  private Button package1Button;
  @InjectView(id = R.id.button2, click = true)
  private Button package2Button;
  @InjectView(id = R.id.button3, click = true)
  private Button package3Button;
  @InjectView(id = R.id.button4, click = true)
  private Button testButton;
  @InjectView(id = R.id.service_card_layout)
  private RelativeLayout mUseServiceCardLayout;

  private PackageDetails mChosenPackage;
  private List<PackageDetails> mPackageList;
  private LeUser mLeUser;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.membership_packages_introduction_layout);
    setTitle("会员套餐");
    mPackageList = new ArrayList<PackageDetails>();
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();

    getPackages(mLeUser.sno, HttpUtils.KEY);
    mChosenPackage = new PackageDetails();

    setTitle_BgColor(0xff7ed2f5);
    this.mUprightButton.setText("购买记录");
    this.mUprightButton.setTextColor(Color.WHITE);
    this.mUprightButton
        .setBackgroundResource(R.drawable.purchase_record_icon_background);
    this.mUprightButton.setPadding(20, 0, 20, 0);
    this.mUprightButton.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {

        v.startAnimation(mPressedAnimation);
        mPressedAnimation.setAnimationListener(new AnimationListener() {

          @Override
          public void onAnimationStart(Animation animation) {

          }

          @Override
          public void onAnimationRepeat(Animation animation) {

          }

          @Override
          public void onAnimationEnd(Animation animation) {

            Intent toPurchaseRecord = new Intent(MembershipCenterActivity.this,
                PurchaseRecordsActivity.class);
            startActivity(toPurchaseRecord);
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
          }
        });
      }
    });

    mUseServiceCardLayout.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {

        startActivity(new Intent(MembershipCenterActivity.this,
            InputActivationActivity.class));
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      }
    });
  }

  private void getPackages(final String sno, final String key) {
    mPackageList.clear();

    showloading("");
    Async
        .start(new Func0<ResponseResult>() {
          @Override
          public ResponseResult call() {

            HashMap<String, Object> param_ = new HashMap<String, Object>();
            param_.put(HttpUtils.TAG_SNO_I, sno);
            param_.put(HttpUtils.TAG_KEY_I, key);

            return HttpUtils.startRequest(HttpUtils.API_URL
                + HttpUtils.GET_PACKAGES, param_, HttpUtils.TAG_GET_REQUEST);

          }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .filter(new Func1<ResponseResult, Boolean>() {

          @Override
          public Boolean call(ResponseResult arg0) {

            boolean r = (arg0 != null && Tools.isNotEmpty(arg0) && arg0
                .isSuccess());
            if (!r) {
              toastShow("获取套餐失败");
            }
            return r;
          }
        }).doOnCompleted(new Action0() {

          @Override
          public void call() {
            dismissLoading();
            int size = mPackageList.size();
            for (int i = 0; i < size; i++) {
              PackageDetails pd = mPackageList.get(i);
              if (i != size - 1)
                addItem(pd, packageRootLayout, true);
              else
                addItem(pd, packageRootLayout, false);
            }
          }
        }).subscribe(new Action1<ResponseResult>() {
          @SuppressWarnings({ "unchecked" })
          @Override
          public void call(ResponseResult arg0) {
            mPackageList = (List<PackageDetails>) JsonSerializer.getInstance()
                .deserialize(arg0.data, ArrayList.class, PackageDetails.class);

          }
        });
  }

  private void addItem(final PackageDetails pd, LinearLayout rootLayout,
                       boolean addSeparator) {
    RelativeLayout rl = new RelativeLayout(this);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    rl.setLayoutParams(params);

    TextView tv1 = new TextView(this);
    RelativeLayout.LayoutParams tvParams1 = new RelativeLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    tvParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    tvParams1.addRule(RelativeLayout.CENTER_IN_PARENT);
    tvParams1.setMargins(Tools.getPixelByDip(this, 20), 0, 0, 0);
    tv1.setLayoutParams(tvParams1);
    tv1.setTextSize(16);
    tv1.setText(pd.name);

    TextView tv2 = new TextView(this);
    RelativeLayout.LayoutParams tvParams2 = new RelativeLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    tvParams2.addRule(RelativeLayout.CENTER_IN_PARENT);
    tvParams2.addRule(RelativeLayout.RIGHT_OF, tv1.getId());
    tvParams2.setMargins(Tools.getPixelByDip(this, 20), 0, 0, 0);
    tv2.setLayoutParams(tvParams2);
    tv2.setTextSize(16);
    tv2.setText("￥" + pd.price);

    Button btn3 = new Button(this);
    RelativeLayout.LayoutParams btnParams3 = new RelativeLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    btnParams3.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    btnParams3.addRule(RelativeLayout.CENTER_IN_PARENT);
    btnParams3.setMargins(0, Tools.getPixelByDip(this, 10),
        Tools.getPixelByDip(this, 10), Tools.getPixelByDip(this, 10));
    btn3.setGravity(Gravity.CENTER);
    btn3.setTextColor(this.getResources().getColor(R.color.white_color));
    btn3.setBackgroundResource(R.drawable.green_round_corner_btns);
    btn3.setText("购买");
    btn3.setPadding(Tools.getPixelByDip(this, 14),
        Tools.getPixelByDip(this, 8), Tools.getPixelByDip(this, 14),
        Tools.getPixelByDip(this, 8));
    btn3.setLayoutParams(btnParams3);
    btn3.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {

        // v.startAnimation(mPressedAnimation);
        // mPressedAnimation.setAnimationListener(new AnimationListener() {
        //
        // @Override
        // public void onAnimationStart(Animation animation) {
        //
        // }
        //
        // @Override
        // public void onAnimationRepeat(Animation animation) {
        //
        // }
        //
        // @Override
        // public void onAnimationEnd(Animation animation) {
        //
        if (pd.price != 0) {
          // Intent toOrderDetails = new Intent(MembershipCenterActivity.this,
          // OrderDetailsActivity.class);
          // toOrderDetails.putExtra("packageName", pd.getName());
          // toOrderDetails.putExtra("monthCount", pd.getPeriod());
          // toOrderDetails.putExtra("totalMoney", pd.getPrice());
          // toOrderDetails.putExtra("productId", pd.getId());
          // startActivity(toOrderDetails);
          // overridePendingTransition(R.anim.push_left_in,
          // R.anim.push_left_out);
        } else {
          toastShow("请选择套餐!");
        }
        // }
        // });
      }
    });

    rl.addView(tv1);
    rl.addView(tv2);
    rl.addView(btn3);

    rootLayout.addView(rl);

    if (addSeparator) {
      View separator = new View(this);
      LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(
          LayoutParams.MATCH_PARENT, Tools.getPixelByDip(this, 1));
      separator.setBackgroundColor(Color.rgb(207, 207, 207));
      separator.setLayoutParams(vp);
      rootLayout.addView(separator);
    }
  }

  @Override
  public void onClick(View v) {

    switch (v.getId()) {
    case R.id.button1:
      mChosenPackage.name = "3个月套餐";// );
      mChosenPackage.period = 3; // );
      mChosenPackage.price = 42; // );
      break;
    case R.id.button2:
      mChosenPackage.name = "6个月套餐";// );
      mChosenPackage.period = 6; // );
      mChosenPackage.price = 72; // );
      break;
    case R.id.button3:
      mChosenPackage.name = "12个月套餐";// );
      mChosenPackage.period = 12; // );
      mChosenPackage.price = 96; // );
      break;
    case R.id.button4:

      mChosenPackage.name = "测试套餐"; // );
      mChosenPackage.period = 0; // );
      mChosenPackage.price = 0.01f; // );

      break;
    default:
      break;
    }
    v.startAnimation(mPressedAnimation);
    mPressedAnimation.setAnimationListener(new AnimationListener() {

      @Override
      public void onAnimationStart(Animation animation) {

      }

      @Override
      public void onAnimationRepeat(Animation animation) {

      }

      @Override
      public void onAnimationEnd(Animation animation) {

        if (mChosenPackage.price != 0) {
          // Intent toOrderDetails = new Intent(MembershipCenterActivity.this,
          // OrderDetailsActivity.class);
          // toOrderDetails.putExtra("packageName", mChosenPackage.getName());
          // toOrderDetails.putExtra("monthCount", mChosenPackage.getPeriod());
          // toOrderDetails.putExtra("totalMoney", mChosenPackage.getPrice());
          // toOrderDetails.putExtra("productId", mChosenPackage.getId());
          //
          // startActivity(toOrderDetails);
          // overridePendingTransition(R.anim.push_left_in,
          // R.anim.push_left_out);
        } else {
          toastShow("请选择套餐!");
        }
      }
    });
  }

}
